package com.kaxiu.service.impl;

import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.kaxiu.config.CommonConstant;
import com.kaxiu.config.redis.RedisService;
import com.kaxiu.persistent.entity.*;
import com.kaxiu.persistent.mapper.OrderItemMapper;
import com.kaxiu.persistent.mapper.OrdersMapper;
import com.kaxiu.persistent.mapper.RepairOrderMapper;
import com.kaxiu.persistent.mapper.SendOrderMapper;
import com.kaxiu.service.IAccountService;
import com.kaxiu.service.IOrdersService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.kaxiu.vo.order.OrderRequestVo;
import com.kaxiu.vo.order.OrderResponseVo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.io.Serializable;
import java.time.LocalDateTime;
import java.util.List;

import static com.kaxiu.config.CommonConstant.OrderStatus.ORDER_STATUS_PAYED_WATTING;
import static com.kaxiu.config.CommonConstant.PayStatus.PAY_STATUS_PAYED;

/**
 * <p>
 * 订单表 服务实现类
 * </p>
 *
 * @author ly
 * @since 2019-08-04
 */
@Service
public class OrdersServiceImpl extends ServiceImpl<OrdersMapper, Orders> implements IOrdersService {

    @Autowired
    private OrdersMapper ordersMapper;

    @Autowired
    private SendOrderMapper sendOrderMapper;

    @Autowired
    private RepairOrderMapper repairOrderMapper;

    @Autowired
    private OrderItemMapper orderItemMapper;

    @Autowired
    private RedisService redisService;

    @Autowired
    private IAccountService accountService;

    @Override
    @Transactional()
    public Serializable takeOrder(OrderRequestVo vo) {
        BasicUser user = redisService.getWxUser();
        if(user != null && user.getId() != null){
            Orders orders = vo.vo2Orders();
            orders.setUserId(user.getId());
            ordersMapper.insert(orders);
            if(orders != null && orders.getId() != null){
                OrderItem orderItem = vo.vo2OrderItem();
                orderItem.setOrderId(orders.getId());
                orderItem.setUserId(user.getId());
                int itemResult = orderItemMapper.insert(orderItem);
                RepairOrder repairOrder = vo.vo2RepairOrder();
                repairOrder.setOrderId(orders.getId());
                repairOrder.setUserId(user.getId());
                int repairResult = repairOrderMapper.insert(repairOrder);
                if(itemResult != 0 && repairResult != 0){
                    return orders.getId();
                }
            }
        }
        return null;
    }

    @Override
    @Transactional
    public int takeOrder(Long orderId, JSONObject location) {
        //当前维修人员
        BasicUser user = redisService.getWxUser();
        Orders orders = ordersMapper.selectById(orderId);
        // 判断如果订单已经是接单状态
        if(orders.getStatus() == CommonConstant.OrderStatus.ORDER_STATUS_RECEIVE){
            return 0;
        }

        SendOrder sendOrder = new SendOrder();
        sendOrder.setRepairOrderId(orderId);
        sendOrder.setUserId(orders.getUserId());
        sendOrder.setStatus(CommonConstant.OrderStatus.ORDER_STATUS_RECEIVE);
        sendOrder.setMaintenanceId(user.getId());
        int sendRes = sendOrderMapper.insert(sendOrder);
        if(sendRes > 0){

            //修改orders表的状态
            orders.setStatus(CommonConstant.OrderStatus.ORDER_STATUS_RECEIVE);
            ordersMapper.updateById(orders);

            //修改repareOrder表的状态与位置和 。。。
            RepairOrder repairUpdate = new RepairOrder();
            repairUpdate.setStatus(CommonConstant.OrderStatus.ORDER_STATUS_RECEIVE);
            //维修人员id
            repairUpdate.setMaintenanceId(sendOrder.getMaintenanceId());
            repairUpdate.setPersonalLocation(location.toJSONString());
            return repairOrderMapper.update(repairUpdate,
                    Wrappers.lambdaUpdate(new RepairOrder()).eq(RepairOrder::getOrderId, orderId));

        }
        return 0;
    }

    @Override
    public IPage<OrderResponseVo> getOrderDetailByUserId(Integer status, Integer pageSize, Integer pageIndex) {
        BasicUser user = redisService.getWxUser();
        return ordersMapper.selectOrderList(
                new Page<>(pageIndex, pageSize)
                , user.getId(), status);
    }

    @Override
    public OrderResponseVo getOrderDetailById(Serializable orderId) {
        return ordersMapper.selectOrderById(orderId);
    }

    @Override
    public int rateById(Serializable orderId, Integer rate, String review) {
        RepairOrder repairOrder = new RepairOrder();
        repairOrder.setStarLevel(rate);
        repairOrder.setReview(review);
        UpdateWrapper<RepairOrder> update = new UpdateWrapper<>();
        update.set("star_level", rate);
        update.set("review", review);
        update.eq("order_id", orderId);
        return repairOrderMapper.update(repairOrder, update);
    }

    @Override
    public List<OrderResponseVo> getEffectiveOrders() {
        return ordersMapper.selectEffectiveOrderList(null);
    }

    @Override
    public IPage<OrderResponseVo> getServerOrder(Integer status, Integer pageIndex, Integer pageSize) {
        BasicUser user = redisService.getWxUser();
        return ordersMapper.selectServerOrders(
                new Page<>(pageIndex, pageSize), user.getId(), status);
    }

    @Override
    @Transactional
    public boolean overOrder(String orderId, String imgFrontPath, String imgOverPath) {
        Orders orders = ordersMapper.selectById(orderId);
        //修改orders表的状态
        orders.setStatus(CommonConstant.OrderStatus.ORDER_STATUS_OVER);
        int result = ordersMapper.updateById(orders);
        if(result > 0){
            //修改repareOrder表的状态与位置和 。。。
            RepairOrder repairUpdate = new RepairOrder();
            repairUpdate.setStatus(CommonConstant.OrderStatus.ORDER_STATUS_OVER);
            repairUpdate.setBeforeRepairPhoto(imgFrontPath);
            repairUpdate.setAfterRepairPhoto(imgOverPath);
            repairUpdate.setFinishedTime(LocalDateTime.now());
            repairOrderMapper.update(repairUpdate,
                    Wrappers.lambdaUpdate(new RepairOrder()).eq(RepairOrder::getOrderId, orderId));
            //修改派单表
            SendOrder sendOrder = new SendOrder();
            sendOrder.setStatus(CommonConstant.OrderStatus.ORDER_STATUS_OVER);
            sendOrder.setFinishedTime(LocalDateTime.now());
            sendOrderMapper.update(sendOrder,
                    Wrappers.lambdaUpdate(new SendOrder()).eq(SendOrder::getRepairOrderId, orderId));
            return accountService.overOrder(orders);
        }
        return false;
    }

    @Override
    @Transactional
    public Boolean paySuccess(Long orderId) {
        //支付成功，修改订单状态
        //todo - 支付成功，修改的订单状态应该有微信的相关订单信息
        Orders orders = this.getById(orderId);
        orders.setId(orderId);
        orders.setPayStatus(PAY_STATUS_PAYED);
        orders.setStatus(ORDER_STATUS_PAYED_WATTING);
        ordersMapper.updateById(orders);

        RepairOrder repairOrder = new RepairOrder();
        repairOrder.setStatus(ORDER_STATUS_PAYED_WATTING);
        RepairOrder repairOrder2 = new RepairOrder();
        repairOrder2.setOrderId(orderId);
        repairOrderMapper.update(repairOrder, Wrappers.lambdaUpdate(repairOrder2).eq(RepairOrder::getOrderId, orderId));

        return accountService.successPayOrder(orders);
    }

    @Override
    public OrderResponseVo getServerOrder() {
        IPage<OrderResponseVo> vo;
        BasicUser user = redisService.getWxUser();
        vo = ordersMapper.selectServerOrders(
                new Page<>(1 ,1), user.getId(), CommonConstant.OrderStatus.ORDER_STATUS_RECEIVE);
        if(vo.getRecords().size() > 0){
            return vo.getRecords().stream().limit(1).findFirst().get();
        }
        return null;
    }
}
